package com.xxl.job.executor.service.jobhandler;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;

@Service
public class JobService {
	
	
	
	public String getCookieFromLogin() {
		try {
			HttpClient client = HttpClientBuilder.create().build();
			HttpPost httpPost = new HttpPost();
			EntityBuilder builder = EntityBuilder.create();
			BasicNameValuePair pair1 = new BasicNameValuePair("userName", "admin");
			BasicNameValuePair pair2 = new BasicNameValuePair("password", "123456");
			builder.setParameters(pair1, pair2);
			HttpEntity entity = builder.build();
			httpPost.setEntity(entity);
			httpPost.setURI(URI.create("http://localhost:8080/xxl-job-admin/login"));
			HttpResponse response = null;
			response = client.execute(httpPost);
			Header[] headers = response.getHeaders("Set-Cookie");
			System.out.println(Arrays.toString(headers));
			String value = headers[0].getValue();
			String cookie = value.substring(value.indexOf("XXL_JOB_LOGIN_IDENTITY=") + "XXL_JOB_LOGIN_IDENTITY=".length(), value.indexOf("; "));
			return cookie;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
